package com.wootion.cims.shiro.config;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.wootion.cims.response.ResponseResult;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.web.filter.authc.BasicHttpAuthenticationFilter;
import org.apache.shiro.web.util.WebUtils;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.RequestMethod;

import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.net.URLEncoder;

@Slf4j
@SuppressWarnings("all")
public class JWTFilter extends BasicHttpAuthenticationFilter {
    public static final String TOKEN_NAME_ONE = "Authorization";
    public static final String TOKEN_NAME_TWO = "X-Token";
    /**
     * @description 是否允许访问，如果带有token，则对token进行检查，否则直接通过
     * @param request
     * @param response
     * @param mappedValue
     * @return boolean
     */
    @Override
    protected boolean isAccessAllowed(ServletRequest request, ServletResponse response, Object mappedValue) {
        if (this.isLoginAttempt(request, response)){
            log.info("token不为null,开始校验token的合法性和有效性....");
            try {
                this.executeLogin(request, response);
                log.info("认证成功");
                return true;
            }catch (Exception e){
                log.info("认证失败");
            }
        }
        log.info("token为null,登陆请求或者访问匿名开放接口");
        return true;
    }

    /**
     * @description  判断用户是否想要登入。检测heade里面是否包含Token字段
     * @param request
     * @param response
     * @return boolean
     */
    @Override
    protected boolean isLoginAttempt(ServletRequest request, ServletResponse response) {
        log.info("检查token是否为null");
        HttpServletRequest httpServletRequest= (HttpServletRequest) request;
        String token=httpServletRequest.getHeader(JWTFilter.TOKEN_NAME_TWO);
        return token != null;//token不是空，返回true
    }

    /**
     * @param request
     * @param response
     * @return boolean
     */
    @Override
    protected boolean executeLogin(ServletRequest request, ServletResponse response) throws Exception {
        HttpServletRequest req= (HttpServletRequest) request;
        String token=req.getHeader(JWTFilter.TOKEN_NAME_TWO);
        JWTToken jwtToken = new JWTToken(token);
        getSubject(request, response).login(jwtToken);
        return true;
    }


    @Override
    protected boolean preHandle(ServletRequest request, ServletResponse response) throws Exception {
        HttpServletRequest httpServletRequest = (HttpServletRequest) request;
        HttpServletResponse httpServletResponse = (HttpServletResponse) response;
        httpServletResponse.setHeader("Access-Control-Allow-Origin", httpServletRequest.getHeader("Origin"));
        httpServletResponse.setHeader("Access-Control-Allow-Methods", "GET,POST,OPTIONS,PUT,DELETE");
        httpServletResponse.setHeader("Access-Control-Allow-Headers", httpServletRequest.getHeader("Access-Control-Request-Headers"));
        if (httpServletRequest.getMethod().equals(RequestMethod.OPTIONS.name())) {
            httpServletResponse.setStatus(HttpStatus.OK.value());
            return false;
        }
        return super.preHandle(request, response);
    }

    /**
     * @description 错误方式一:返回token认证错误,直接向前段返回错误的json信息
     * @param response
     * @param msg
     */
    private void responseTokenError(ServletResponse response, String msg) {
        log.info("token解析错误，开始执行responseTokenError()方法");
        HttpServletResponse httpServletResponse = WebUtils.toHttp(response);
        httpServletResponse.setCharacterEncoding("UTF-8");
        httpServletResponse.setStatus(HttpStatus.OK.value());
        httpServletResponse.setContentType("application/json; charset=utf-8");
        try (PrintWriter out = httpServletResponse.getWriter()) {
            ObjectMapper objectMapper = new ObjectMapper();
            String content = objectMapper.writeValueAsString(ResponseResult.builder().message(msg).code((long)HttpStatus.FORBIDDEN.value()).build());
            out.append(content);
        } catch (IOException e) {
            log.error("返回token认证错误信息失败！{}", e.getMessage());
        }
    }
    /**
     * @description  错误方式二:返回token认证错误,直接跳转到我们返回无权限的接口
     * 由我们的/unauthorized/{message}接口返回失败的json信息
     * @param response
     * @param message
     */
    private void responseError(ServletResponse response, String message) {
        log.info("token解析错误，开始执行responseError()方法");
        try {
            HttpServletResponse httpServletResponse = (HttpServletResponse) response;
            //设置编码，否则中文字符在重定向时会变为空字符串
            message = URLEncoder.encode(message, "UTF-8");
            httpServletResponse.sendRedirect("/unauthorized/" + message);
        } catch (IOException e) {
            System.out.println(e.getMessage());
        }
    }
}
